package xyz.kongbai121.demo.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xyz.kongbai121.demo.domain.RespBean;
import xyz.kongbai121.demo.domain.User;
import xyz.kongbai121.demo.service.ILoginService;
import xyz.kongbai121.demo.util.HttpUtil;

import java.util.HashMap;
import java.util.Map;


/**
 * 登录处理控制器
 *
 * @author 空白
 */
@RestController
public class LoginController {

    @Autowired
    private ObjectMapper jsonMapper;
    @Autowired
    private ILoginService service;
    @Value("${wx.loginURL}")
    private String loginURl;
    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.secret}")
    private String secret;
    @Value("${wx.grantType}")
    private String grantType;

    @RequestMapping("/login")
    public Map<String, String> login(String code) {
        Map<String, String> map = new HashMap<>();
        User user = new User();
        String httpURL = loginURl;
        HashMap<String, String> reqMap = new HashMap<>();
        reqMap.put("appid", appid);
        reqMap.put("secret", secret);
        reqMap.put("js_code", code);
        reqMap.put("grant_type", grantType);
        //向微信发出登录凭证校验
        try {
            String resp = HttpUtil.sendHttpRequest(httpURL, reqMap);
            JsonNode jsonNode = jsonMapper.readTree(resp);
            JsonNode openid = jsonNode.get("openid");
            user.setOpenid(openid.toString().replaceAll("\"", ""));
        } catch (Exception e) {
            e.printStackTrace();
            return map;
        }
        String token = service.login(user);
        map.put("token", token);
        return map;
    }

    //用户令牌有效期延迟
    @RequestMapping("/register")
    public RespBean register(String token, String nickName, String avatarUrl, String gender, String province) {
        User msg = service.register(token, nickName, avatarUrl, gender, province);
        return new RespBean(true, msg);
    }

    @RequestMapping("/logout")
    public RespBean logout(String token) {
        String msg = service.logout(token);
        return new RespBean(true, msg);
    }

    @RequestMapping("/delayed")
    public RespBean delayed(String token) {
        String msg = service.delayed(token);
        return new RespBean(true, msg);
    }

    @RequestMapping("/getUserInfo")
    public RespBean getUserInfo(String token) {
        return new RespBean(true, service.getUserInfo(token));
    }
}
